package com.dao;

import com.pojo.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDao extends BaseDao<User>{
    @Override
    public User rowMapper(ResultSet rs) {
        User user = new User();
        try {
            user.setId(rs.getInt("id"));
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setSex(rs.getInt("sex"));
            user.setRoleId(rs.getInt("role_id"));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return user;
    }

    //查询用户
    public User searchByUnameAndPwd(String username, String password) {
        String sql = "SELECT username,password,sex,id,role_id FROM user WHERE username = ? AND password = ? AND role_id = 1";
        Object[] arr = {username,password};
        return this.find(sql,arr);
    }

    public int addUser(User user) {
        String sql = "INSERT INTO user(username,password,sex,is_deleted)VALUES(?,?,?,0)";
        Object[] arr = {user.getUsername(),user.getPassword(),user.getSex()};
        if (this.update(sql,arr))
            return 1;
        else return 0;
    }

    public List<User> searchAll() {
        String sql = "SELECT id,username,password,sex, role_id FROM user where is_deleted = 0 OR is_deleted is null";
        return this.findMultiple(sql,null);
    }

    public int deleteUser(String username) {
        String sql = "UPDATE user set is_deleted = 1 WHERE username = ?";
        Object[] arr = {username};
        if (this.update(sql,arr))
            return 1;
        else return 0;
    }
}
